import java.io.*;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 * 客户端处理类
 */
class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
             DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()))) {

            //设置超时防止无限等待
            socket.setSoTimeout(10000);

            short type = in.readShort();
            //接受到客户端的1
            if (type == 1) {
                int n = in.readInt();
                System.out.println("收到初始化消息，N = " + n);
                out.writeShort(2); //发送同意消息 (Type=2)
                out.flush();

                for (int i = 0; i < n; i++) {
                    type = in.readShort();
                    //收到客户端的发送分块
                    if (type == 3) {
                        int length = in.readInt();
                        byte[] data = new byte[length];
                        in.readFully(data);
                        String input = new String(data, "UTF-8");

                        //显示接收的原始文本
                        System.out.println("收到第 " + (i+1) + " 块: " + input);

                        //反转文本块
                        String reversed = new StringBuilder(input).reverse().toString();
                        byte[] reversedData = reversed.getBytes("UTF-8");

                        //发送反转结果
                        out.writeShort(4); // Type=4
                        out.writeInt(reversedData.length);
                        out.write(reversedData);
                        out.flush();
                        System.out.println("发送第 " + (i+1) + " 块反转结果: " + reversed);
                    }
                }
            }
        } catch (SocketTimeoutException e) {
            System.err.println("连接超时: " + e.getMessage());
        } catch (EOFException e) {
            System.err.println("客户端提前关闭连接");
        } catch (IOException e) {
            System.err.println("客户端处理异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}